package com.zoho.daliansheng.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zoho.daliansheng.utils.JwtUtils;
import com.zoho.daliansheng.utils.ResultUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ///*
        // 验证token
        //log.info("------------- LoginInterceptor 开始 -------------");
        long startTime = System.currentTimeMillis();
        request.setAttribute("requestStartTime", startTime);

        // OPTIONS请求不做校验,
        // 前后端分离的架构, 前端会发一个OPTIONS请求先做预检, 对预检请求不做校验
        if (request.getMethod().toUpperCase().equals("OPTIONS")) {
            return true;
        }

        String path = request.getRequestURL().toString();
        //log.info("接口登录拦截：path：{}", path);

        //获取header的token参数
        String tokenHead = request.getHeader(JwtUtils.TOKEN_HEADER);
        //log.info("登录校验开始，tokenHead：{}", tokenHead);
        if (tokenHead == null || tokenHead.isEmpty()) {
            String msg = "token为空，请求被拦截";
            //log.info(msg);
            resultMessage(response, ResultUtil.error(msg));
            return false;
        }

        if (!tokenHead.startsWith(JwtUtils.TOKEN_PREFIX)) {
            String msg = "token前缀不合法，请求被拦截";
            //log.info(msg);
            resultMessage(response, ResultUtil.error(msg));
            return false;
        }

        //去掉前缀，获取token字符串
        String token = tokenHead.replace(JwtUtils.TOKEN_PREFIX, "");

        Claims claims = JwtUtils.checkToken(token);
        //获取用户ID
        if (claims == null) {
            String msg = "token无效";
            //log.info(msg);
            resultMessage(response, ResultUtil.error(msg));
            return false;
        } else {
            //String userId = (String) claims.get("userId");
            //String userName = (String) claims.get("username");
            //log.info("已登录");
            return true;
        }
        //*/
        //return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //long startTime = (Long) request.getAttribute("requestStartTime");
        //log.info("------------- LoginInterceptor 结束 耗时：{} ms -------------", System.currentTimeMillis() - startTime);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //log.info("LogInterceptor 结束");
    }

    public static void resultMessage(HttpServletResponse response, Object obj) {
        try {
            response.reset();
            ObjectMapper objectmapper = new ObjectMapper();
            response.setContentType("application/json;Charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.print(objectmapper.writeValueAsString(obj));
            writer.close();
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
